<template>
    <rui-page :defines="defines">
        <Row>
            <Alert>
                融资校验方案信息
            </Alert>
        </Row>
        <Form ref="showResultForm" :model="schemeResultForm" :lable-width="250" :rules="rulesSchemeForm">
            <Row>
                <Col :xs="24" :md="24" :lg="16" :xl="12" v-if="op!='add'">
                    <FormItem label="方案编号" prop="planNo" :label-width="100">
                        <Input v-model="schemeResultForm.planNo" style="width: 250px" :disabled="readonlyNo" maxlength="32"/>
                    </FormItem>
                </Col>
                <Col :xs="24" :md="24" :lg="16" :xl="12">
                    <FormItem label="方案名称" prop="name" :label-width="100">
                        <Input style="width: 250px" v-model="schemeResultForm.name" :disabled="readonlyName" maxlength="128"/>
                    </FormItem>
                </Col>
            </Row>
        </Form>
        <Row style="text-align: center;">
            <Button @click="save" icon="md-bookmark" type="primary" v-show="op!='view'">保存</Button>
        </Row>
        <br>
        <Row>
            <Alert>
                融资校验规则信息
            </Alert>
        </Row>
        <div>
            <rui-table
                :defineId="'defineTable'"
                :fixedLeft="['action']"
                :showIndex="false"
                :select="false"
                :columns="showColumns"
                :slots="[{key:'action',slot:'action'}]"
                @loadDatas="queryData"
                ref="showTable"
            >
                <template slot="toolBar">
                    <Button @click="add" icon="md-add"  v-show="op!='view'" type="primary">新增</Button>
                </template>
                <template slot="action" slot-scope="{ row, index }">
                    <div>
                        <Button @click="edit(row)" size="small" type="primary">编辑</Button>
                        <Button type="error" size="small" @click="remove(row)">删除</Button>
                        <Button @click="ruleConfig(row)" size="small" type="warning">规则配置</Button>
                    </div>
                </template>
            </rui-table>
        </div>
        <Modal
            v-model="isShowRule"
            :title="ruleTitle"
            :width="800"
            :closable="false"
            :mask-closable="false"
            @on-ok="saveRule">
            <rui-form  :form-options="ruleFormOptions" :label-width="120" :read-only="false" ref="ruleForm"/>
            <div slot="footer">
                <Button size="small" @click="isShowRule = false">取消</Button>
                <Button type="primary" size="small" @click="saveRule">保存</Button>
            </div>
        </Modal>

        <Modal
            v-model="dataLoad"
            :title="ruleConfigTitle"
            :width="1000"
            :closable="false"
            :mask-closable="false">
            <rule-tree v-if="dataLoad" :rule-data="ruleData" :ruleAtoms="ruleAtoms" :ruleName="ruleName" :ruleGroup="ruleGroup" :businessScenario="businessScenario" @saved="returnRuleId" :rule-id="ruleId"/>
            <div slot="footer">
                <Button size="small" @click="dataLoad = false">取消</Button>
            </div>
        </Modal>
       <Row style="text-align: center;">
            <Button @click="close" icon="md-backspace" type="primary">返回</Button>
        </Row>
    </rui-page>
</template>
<script>
    import planDefine from "./finance-plan-define";
    import tableDefine from "../defines/product-rule-info-define";
    import ruiRules from '_c/rui-auto/rui-rules/index';
    import {loadRuleDataById} from '_p/basic/api/rule/rule';
    import {queryAtomsByBizType} from "@/projects/basic/api/rule/ruleAtom";
    import {deepClone} from "@/libs/utils/ObjectClone";
    import {
        getRuleInfoList,
        delById,
        addRule,
        editRule,
    } from "@/projects/afs-core-business/api/afs-product/product-rule/product-rule-info";
    import {
        saveFinancePlan,
    } from "@/projects/afs-core-business/api/afs-product/product-plan-select/financePlan";

    import {saveRuleOut} from '_p/basic/api/rule/rule';
    import {getUri} from "@/libs/tools";

    export default {
        components: {
            ruleTree:ruiRules
        },
        props: {
            //状态
            op:{
                type:String,
                required: true,
                default: 'view'
            },
            //方案ID
            planId:{
                type:String,
            },
            //方案场景
            fitScope:{
                type:String,
                required: true,
                default: '006'
            },
            //表单
            schemeForm:{
                type:Object,
            },
        },
        data() {
            return {
                //只读
                readonlyNo:true,
                //只读
                readonlyName:true,
                //校验
                rulesSchemeForm: {
                    planNo: [{required: true, message: " 不能为空",trigger: "blur"}],
                    name: [{required: true, message: " 不能为空",trigger: "blur"}],
                },
                schemeResultForm:{
                    status:'0',
                },

                isShowRule: false,//规则输出信息页面展示
                ruleTitle: null,//规则输出信息页面主题

                modalType:0,
                showColumns: [],

                ruleFormOptions: [
                    {
                        isGroup: false,
                        grids: [
                            {defineId: 'defineTable', span: 24, fields: ['ruleName']},
                            {defineId: 'defineTable', span: 24, fields: ['outputInfo']},
                        ]
                    }
                ],

                dataLoad:false,//规则配置页面开关
                ruleConfigTitle: null,//规则配置页面主题
                ruleAtoms:[],//规则原子
                ruleName:'融资校验规则配置',
                ruleGroup:'financePlanRule',//规则组
                businessScenario:'businessScenario',//规则编号
                ruleId : null,//规则返回的规则ID
                ruleData:[],//规则数据
                row:{},

            };
        },
        computed: {
            defines() {
                return [
                    {
                        id: "defineTable",
                        fields: tableDefine
                    },
                    {
                        id: "definePlan",
                        fields: planDefine
                    }
                ];
            }
        },
        methods: {

            //初始化
            refreshCom(){
                if("view"==this.op){
                    this.readonlyNo = true;
                    this.readonlyName = true;
                    this.showColumns = ['ruleName', 'outputInfo','ruleExpress'];
                    this.schemeResultForm = this.schemeForm;
                    this.refresh();
                }
                if("add"==this.op){
                    this.readonlyNo = false;
                    this.readonlyName = false;
                    this.showColumns = ['action', 'ruleName', 'outputInfo','ruleExpress'];
                }
                if("edit"==this.op){
                    this.readonlyNo = true;
                    this.readonlyName = false;
                    this.showColumns = ['action', 'ruleName', 'outputInfo','ruleExpress'];
                    this.schemeResultForm = this.schemeForm;
                    this.refresh();
                }
            },
            //列表查询
            queryData(pageNumber,pageSize) {
                let queryData = {
                    pageNumber:pageNumber,
                    pageSize:pageSize,
                    planId:this.planId,
                    fitScope:this.fitScope,
                };
                getRuleInfoList(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.showTable.updateTableData(records, total);
                    }
                });
            },
            refresh() {
                this.$refs['showTable'].reloadData();
            },
            close(){
                this.$emit('next', "退回");
            },
            save(){
                this.$refs.showResultForm.validate(valid1 => {
                    if(valid1) {
                        let param = this.schemeResultForm;
                        param["fitScope"]=this.fitScope;
                        param["planId"]=this.planId;
                        //风险定价
                        console.info("风险定价数据保存："+JSON.stringify(param));
                        saveFinancePlan(param).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("保存成功！");
                                //编号只读
                                this.readonlyNo = true;
                                this.schemeResultForm = res.data;
                                //返回信息
                                this.$emit('backInfo', res.data);
                            }
                        });
                    }
                });
            },
            add() {
                if (this.schemeForm.id!=null) {
                    this.ruleTitle = "新增规则";
                    this.isShowRule = true;
                    this.modalType = 0;
                    this.$refs.ruleForm.setAllFieldRequired(true);
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFrom();
                    });
                }else{
                    this.$Message.error('请先填写方案信息并保存!');
                }
            },
            edit(row) {
                this.$refs.ruleForm.resetFrom();
                this.ruleTitle = "编辑规则";
                this.isShowRule = true;
                this.modalType = 1;
                this.$refs.ruleForm.updateFormData(deepClone(row));
                this.$refs.ruleForm.setAllFieldRequired(true);
            },
            ruleConfig(row) {
                this.row = row;
                this.ruleId = row.ruleId;
                this.ruleName=row.ruleName;
                this.businessScenario = row.id;
                this.ruleGroup = row.planId;
                this.ruleConfigTitle = "编辑规则";
                if(row.ruleId!=null){
                    loadRuleDataById(this.ruleId).then(res => {
                        if(res.code='0000'){
                            if(res.data.length>0) {
                                this.ruleData=res.data;
                                this.dataLoad = true;
                            }
                        }
                    });
                }else{
                    this.ruleData = [];
                    this.dataLoad = true;
                }
            },
            remove(v) {
                this.$Modal.confirm({
                    title: "确认删除吗",
                    content: "您确认要删除这条规则?",
                    onOk: () => {
                        delById(v.id).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.refresh();
                            }
                        });
                    }
                });
            },
            saveRule() {
                this.$refs.ruleForm.getForm().validate(valid => {
                    if (valid) {
                        if (this.modalType === 0) {
                            let param = this.$refs.ruleForm.getFormData();
                            param.planId = this.planId;
                            param.fitScope = this.fitScope;
                            addRule(param)
                                .then(res => {
                                    if (res.code === "0000") {
                                        this.$Message.success("操作成功");
                                        this.refresh();
                                        this.isShowRule = false;
                                    }
                                })
                                .catch(() => {
                                    this.refresh();
                                });
                        } else {
                            let param = this.$refs.ruleForm.getFormData();
                            editRule(param)
                                .then(res => {
                                    if (res.code === "0000") {
                                        this.$Message.success("操作成功");
                                        this.refresh();
                                        this.isShowRule = false;
                                    }
                                })
                                .catch(() => {
                                    this.refresh();
                                });
                            if(param.ruleId!=null){
                                this.saveRuleOut(param.ruleId,param.outputInfo);
                            }
                        }
                    }
                });
            },
            returnRuleId(ruleId,expressValue){
                this.ruleId = ruleId;
                console.log(ruleId);
                this.dataLoad = false;
                // 编辑
                this.row.ruleId = ruleId;
                this.row.ruleExpress = expressValue;
                this.row.activeStatus = "0";
                editRule(this.row)
                    .then(res => {
                        if (res.code === "0000") {
                            this.refresh();
                        }
                    })
                    .catch(() => {
                        this.refresh();
                    });
                this.saveRuleOut(ruleId,this.row.outputInfo);
            },
            saveRuleOut(ruleId,outputInfo){
                let rule = {
                    "id":ruleId,
                    "ruleOut":outputInfo
                };
                saveRuleOut(rule,getUri('rule')).then(res => {
                    if (res.code === "0000") {
                        this.refresh();
                    }
                }).catch(() => {
                    this.$Message.error("规则输出保存失败！");
                });
            },
        },
        mounted() {
            this.refreshCom();
            queryAtomsByBizType(this.fitScope,'product').then(res => {
                if (res.code === "0000") {
                    this.ruleAtoms = res.data;
                }
            });
        },
    };
</script>
